import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, usePageResponseSuccess, useResponseSuccess, customResponse } from '~/utils/response';
import { queryDatabase } from '~/functions';

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  try {
    let queryString;
    const args = [];
    // 读取POST请求的请求体，获取查询参数
    const { page, pageSize, orderNo, clientName, sortBy, sortOrder } = await readBody(event);

    // 返回数据的列
    const columns = [
      'clientName',
      'contactPerson',
      'orderNo',
      'sampleName',
      'sampleNo',
      'modelSpec',
      'quantity',
      'testItems',
      'currentProgress',
      'sampleStatus',
      'receiver',
      'receiveDate',
      'sampleHandling',
      'analysisDate',
      'tester',
      'processDate',
      'processor',
      'reportNo',
      'remarks',
      'reportNotes',
      'othersNotes',
    ];

    // 处理排序字段和排序顺序
    let finalSortBy = sortBy || 'orderNo';
    let finalSortOrder = sortOrder || 'DESC';
    // 根据 orderNo 和 clientName 构建查询语句
    if (!orderNo && !clientName) {
      // 如果 orderNo 和 clientName 均为空，则查询所有数据
      queryString = `SELECT ${columns.join(', ')} FROM samplelists ORDER BY ? ?`;
    } else {
      // 如果 orderNo、clientName 有一个不为空或者都不为空时，查询满足要求的数据
      let whereClause = [];
      if (orderNo) {
        whereClause.push('orderNo = ?');
        args.push(orderNo);
      }
      if (clientName && clientName.length > 0) {
        const clientNameConditions = clientName.map(() => 'JSON_CONTAINS(clientName, JSON_QUOTE(?))').join(' AND ');
        whereClause.push(clientNameConditions);
        args.push(...clientName);
      }
      queryString = `SELECT ${columns.join(', ')} FROM samplelists WHERE ${whereClause.join(' AND ')} ORDER BY ? ?`;
    }
    // 合并排序的参数
    args.push(finalSortBy, finalSortOrder);

    // 调用 queryDatabase 函数执行操作
    const results = <any[]>await queryDatabase(queryString, args);
    if (results.length <= 0) {
      return useResponseSuccess({ message: '未查询到匹配的数据' });
    } else {
      return usePageResponseSuccess(page as string, pageSize as string, results);
    }
  } catch (error) {
    return customResponse(-2, error.message);
  }
});
